import ala from 'ala'
/**
 * 系统所有的路由信息，和服务端对应
 */
export async function themeRoute() {
  var themeType = ala.themeType()

  if (themeType !== 'admin') {
    var route = ala.router()
    if (route.fullPath.toLowerCase().indexOf(`/admin-${themeType}/index.html#`) > -1) {
      var hash = route.hash
      if (hash) {
        ala.push(hash.replace('#', ''))
      }
    }
  }
  var result
  if (themeType) {
    var routes = await themeRoutes()
    routes.forEach(element => {
      if (element.type.toLowerCase() === themeType.toLowerCase()) {
        result = element
      }
    })
  }
  if (!result) {
    ala.push('/404')
    return
  }
  checkSign(themeType, result)
  return result
}


/**
 * 模板类型
 */
export function themeType() {
  var router = ala.router()
  var themetype = 'admin'
  if (router.meta && router.meta.themetype) {
    themetype = router.meta.themetype
  } else {
    themetype = router.params.themetype
  }
  themetype = themetype.toLowerCase()
  if (!themetype) {
    ala.alert('模板信息访问出错,请输入正确的访问网址')
    return
  }
  return themetype
}

/**
 * 检查签名信息
 * @param {*} themeType 
 * @returns 
 */
function checkSign(themeType, result) {
  if (themeType !== 'admin') {
    return
  }
  var route = ala.router()
  if (route.path.toLowerCase().indexOf('/admin/login') > -1) {
    if (result.sign) {
      var pathSplit = route.path.split('/')
      if (pathSplit[pathSplit.length - 1] === result.sign) {
        ala.localSet('security_sign', pathSplit[pathSplit.length - 1], true)
      } else {
        ala.localRemove('security_sign')
      }
    }
  }
  if (route.path.toLowerCase().indexOf('/admin/login') > -1) {
    if (themeType === 'admin' && result.sign) {
      if (route.params.sign !== result.sign) {
        ala.alert('后台访问地址入口不正确，您无权访问')
        ala.push('/web/home')
        setTimeout(function () {
          window.location.reload()
        }, 200)
      }
    }
  }
}
/**
 * 系统所有的路由信息，和服务端对应
 */
export async function themeRoutes() {
  var result = ala.vuexLocalGet('theme_routes', true)
  if (!result) {
    result = await ala.httpGet('api/theme/Routes')
    ala.vuexLocalSet('theme_routes', result, true)
  }
  return result
}

/**
 * 当前访问的模板Id
 */
export function themeId() {
  var allPageInfo = ala.vuexLocalGet(ala.themePageCacheKey())
  if (allPageInfo && allPageInfo.theme) {
    return allPageInfo.theme.id
  }
}
